package org.demo.jms;

import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;

/**
 * 
 * @author  
 * @date    2010-12-30
 * @file    org.demo.jms.QueueListener.java
 */
public class QueueListener implements MessageListener{

	private static final String url = "tcp://localhost:61616";
	private static final String queue = "plan";
	
	private Connection conn = null;
	private Session session = null;
	
	/**
	 * @param args
	 */
	public static void main(String[] args)throws Exception {
		
		QueueListener listener = new QueueListener();
		listener.init();
		
		Destination destination = listener.session.createQueue(queue);
		MessageConsumer consumer = listener.session.createConsumer(destination);
		consumer.setMessageListener(listener);
	}
	/**
	 * 初始化 jms
	 * @return
	 * @throws JMSException
	 */
	public void init() throws JMSException{
		
		ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(url);
		conn = factory.createConnection();
		conn.start();
		
		session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
	}
	/**
	 * 监听消息
	 */
	@Override
	public void onMessage(Message msg) {
		try {
			if (msg instanceof TextMessage){
				TextMessage txtMsg = (TextMessage)msg;
				String data = txtMsg.getText();
				System.out.println(data);
			} else {
				System.out.println(">> " + msg.getClass());
			}
		} catch (Exception e){
			e.printStackTrace();
		} finally {
			try {
				session.close();
			    conn.close(); 
			} catch(Exception e){
				e.printStackTrace();
			}
		}
	}
}
